package com.qining618.cms.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.qining618.common.interceptor.AuthenticationInterceptor;
import com.qining618.common.interceptor.HeaderParamsCheckInterceptor;
import com.qining618.common.interceptor.TraceIdInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @author iqiao
 * @date 2019/8/18 0018.
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String apiPath = "/**";

        // 同一次请求traceId相同
        registry.addInterceptor(new TraceIdInterceptor()).addPathPatterns(apiPath);

        // 请求头参数
        registry.addInterceptor(new HeaderParamsCheckInterceptor()).addPathPatterns(apiPath);

        // 登录验证
        registry.addInterceptor(authenticationInterceptor).addPathPatterns(apiPath);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter jsonMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();

        config.setSerializerFeatures(
                //设置WriteEnumUsingToString
                SerializerFeature.WriteEnumUsingToString,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse
        );
        jsonMessageConverter.setFastJsonConfig(config);

        converters.add(jsonMessageConverter);
        super.addDefaultHttpMessageConverters(converters);
    }
}
